﻿using BaseGrpcEFCore.Entity;
namespace BaseGrpcServer.Repository
{
    public class UserRepository :IUserRepository
    {
        private readonly BaseDbContext _dBContext;
        public UserRepository(BaseDbContext dBContext)
        {
            _dBContext = dBContext;
        }

        public IEnumerable<User> GetAll(Func<User,bool> predicate = null)
        {
            if (predicate != null)
            {
                return _dBContext.Users.Where(x => !x.IsDel).Where(predicate).ToList();
            }
            return _dBContext.Users.Where(x => !x.IsDel).ToList();
        }
        public IEnumerable<User> GetAll(int page, int pagesize)
        {
            return _dBContext.Users.Where(x => !x.IsDel).Skip((page-1)*pagesize).Take(pagesize).ToList();
        } 

        public int Create(User entity)
        {
            try
            {
                _dBContext.Users.Add(entity);
                return _dBContext.SaveChanges();
            }
            catch (Exception)
            {
                return -1;
            }
        }

        public int Update(long longId, User entity)
        {
            try
            {                
                var oldEntity = _dBContext.Users.FirstOrDefault(_ => _.Id.Equals(longId));
                if (oldEntity != null)
                {
                    oldEntity.Name = entity.Name;
                    oldEntity.Role = entity.Role;
                    oldEntity.Account = entity.Account;
                    oldEntity.Email = entity.Email;
                    //注意，这里有时候不应该全量更新
                    var t = _dBContext.Users.Update(oldEntity);
                    return _dBContext.SaveChanges();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            return -1;
        }

        public int MultiDelete(string ids)
        {
            ids = $",{ids},";
            var entities = _dBContext.Users.Where(x => ids.Contains("," + x.Id.ToString() + ",")).ToList();
            entities.ForEach(x => x.IsDel = true);
            _dBContext.Users.UpdateRange(entities);
            return _dBContext.SaveChanges();
        }

        public bool EnsureCreated()
        {
            return _dBContext.Database.EnsureCreated();
        }
    }
}
